package com.ship.contract.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ship.common.core.base.Page;
import com.ship.common.core.enums.MessageTypeEnum;
import com.ship.common.core.enums.ModuleUrlEnum;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.DateUtil;
import com.ship.common.core.utils.DateUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.contract.bean.*;
import com.ship.contract.bean.vo.*;
import com.ship.contract.mapper.*;
import com.ship.contract.service.*;
import com.ship.contract.utils.FileUtil;
import com.ship.contract.utils.ObjectUtils;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.RemoteDispatchService;
import com.ship.system.api.RemoteMessageSendService;
import com.ship.system.api.domain.SysMessageSend;
import com.ship.system.api.domain.dispatch.ShipInfoUpdateDto;
import com.ship.system.api.model.ProcessInstanceParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service("ConShippingService")
public class ConShippingServiceImpl extends ContractBaseServiceImpl<ConShippingMapper, ConShipping> implements ConShippingService {

    @Autowired
    private ConstantMapper constantMapper;

    @Autowired
    private ConShippingMapper conShippingMapper;

    @Autowired
    private ConOperateService conOperateService;

    @Autowired
    private ConAllLabelService conAllLabelService;

    @Autowired
    private ConFilesService conFilesService;

    @Autowired
    private SpInformationService spInformationService;

    @Autowired
    private ConExcellentCasesService conExcellentCasesService;

    @Autowired
    private ConResourceMemorandumPositionService conResourceMemorandumPositionService;

    @Autowired
    private ConResourceMemorandumPositionMapper conResourceMemorandumPositionMapper;

    @Autowired
    private SpInformationMapper spInformationMapper;

    @Resource
    BpmInstanceService bpmInstanceService;

    @Resource
    private RemoteDispatchService remoteDispatchService;

    @Resource
    private RemoteMessageSendService remoteMessageSendService;

    @Autowired
    private IhsShipBaseMapper ihsShipBaseMapper;

    @Value("${file.http-domain}")
    private String httpUrl;
    @Value("${file.https-domain}")
    private String httpsUrl;

    @Override
    public void delApply(Long id) {
        ConShipping conShipping = super.getById(id);
        if(conShipping == null){
            throw new BusException("删除申请失败!,该合同不存在", BaseResultCode.GENERAL_ERROR);
        }
        if(conShipping.getDelApply()==1){
            throw new BusException("当前合同已发起删除申请，请勿重复提交", BaseResultCode.GENERAL_ERROR);
        }
        conShipping.setDelApply(1);
        //启动删除审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(id);
        param.setBpmKey(BpmInstanceService.SYSTEM_DELETE_BPM_KEY);
        Map<String,Object> map = new HashMap<>();
        map.put("serviceType",2);
        map.put("module","con");
        map.put("moduleName","船运合同");
        map.put("reason","");
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conShipping.setDeleteProcessInstanceId(processInstanceId);
        //conShipping.setDelApply(true);
        super.updateById(conShipping);
    }

    @Override
    public Map<String,Object> detail(Long id) {
        Map<String, Object> result = new HashMap<>();
        ConShipping conShipping = super.getById(id);
        result.put("optRecord", conOperateService.listByConId(id));
        result.put("contractLabels", conAllLabelService.listByConId(id));
        List<ConFiles> conFiles = conFilesService.listByConId(id);
        if(conFiles!=null && conFiles.size()>0){
            conFiles.stream().forEach(c->{
                c.setNewUrl(c.getUrl());
                c.setUrl(c.getUrl().replace(httpUrl, httpsUrl));
            });
        }
        result.put("files",conFiles);
        String hireTimeValue = conShipping.getHireTimeValue();
        String rentTimeSlot = conShipping.getRentTimeSlot();
        String deliveryNotice = conShipping.getDeliveryNotice();
        String redeliveryNotice = conShipping.getRedeliveryNotice();
        if (hireTimeValue != null){
            try {
                // 将 hireTimeValue 转换为 JSON 对象
                ObjectMapper objectMapper = new ObjectMapper();
                System.out.println(hireTimeValue);
                List<HireTimeDetails> hireTimeList = objectMapper.readValue(hireTimeValue, new TypeReference<List<HireTimeDetails>>() {
                });

                // 将转换后的 JSON 对象存储到 ConShipping 的 hireTime 中
                conShipping.setHireTime(hireTimeList);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                List<HireTimeDetails> hireTimeList = new ArrayList<>();
                conShipping.setHireTime(hireTimeList);
            }
        }else {
            conShipping.setHireTime(new ArrayList<>());
            conShipping.setHireTimeValue("");
        }
        //交船通知
        if (StringUtils.isNotBlank(deliveryNotice)){
            try {
                // 将 deliveryNotice 转换为 JSON 对象
                ObjectMapper objectMapper = new ObjectMapper();
                List<DeliveryNoticeDetail> deliveryNoticeDetails = objectMapper.readValue(deliveryNotice, new TypeReference<List<DeliveryNoticeDetail>>() {
                });
                conShipping.setDeliveryNoticeList(deliveryNoticeDetails);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                List<DeliveryNoticeDetail> deliveryNoticeDetails = new ArrayList<>();
                conShipping.setDeliveryNoticeList(deliveryNoticeDetails);
            }
        }else {
            conShipping.setDeliveryNoticeList(new ArrayList<>());
            conShipping.setDeliveryNotice("");
        }
        //还船通知
        if (StringUtils.isNotBlank(redeliveryNotice)){
            try {
                // 将 deliveryNotice 转换为 JSON 对象
                ObjectMapper objectMapper = new ObjectMapper();
                List<DeliveryNoticeDetail> deliveryNoticeDetails = objectMapper.readValue(redeliveryNotice, new TypeReference<List<DeliveryNoticeDetail>>() {
                });
                conShipping.setRedeliveryNoticeList(deliveryNoticeDetails);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                List<DeliveryNoticeDetail> deliveryNoticeDetails = new ArrayList<>();
                conShipping.setRedeliveryNoticeList(deliveryNoticeDetails);
            }
        }else {
            conShipping.setRedeliveryNoticeList(new ArrayList<>());
            conShipping.setRedeliveryNotice("");
        }
        if (StringUtils.isNotBlank(rentTimeSlot)){
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                List<ConShippingRent> shipRentList = objectMapper.readValue(rentTimeSlot, new TypeReference<List<ConShippingRent>>() {
                });

                // 将转换后的 JSON 对象存储到 ConShipping 的 hireTime 中
                conShipping.setRentList(shipRentList);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                List<ConShippingRent> shipRentList = new ArrayList<>();
                conShipping.setRentList(shipRentList);
            }
        }else {
            List<ConShippingRent> conShippingRents = new ArrayList<>();
            ConShippingRent conShippingRent = new ConShippingRent();
            conShippingRent.setRentDateBegin(conShipping.getDeliveryDateBegin());
            conShippingRent.setRentDateEnd(conShipping.getRedeliveryDateEnd());
            conShippingRent.setRentParagraph(conShipping.getRent());
            conShippingRent.setRentUnit(conShipping.getCurrency());
            conShippingRents.add(conShippingRent);
            conShipping.setRentList(conShippingRents);
            //conShipping.setRentTimeSlot("");
        }
        result.put("data", conShipping);
        return result;
    }

    @Override
    public void excellent(ConExcellentCases conExcellentCases, String currentUserName) {
        ConShipping conShipping = super.getById(conExcellentCases.getId());
        if(conShipping == null){
            throw new BusException("申请失败!,该合同不存在",BaseResultCode.GENERAL_ERROR);
        }
        ConExcellentCases existByConId = conExcellentCasesService.getAllByConId(conExcellentCases.getId());
        if(existByConId != null){
            throw new BusException("该合同已经存在优秀案例",BaseResultCode.GENERAL_ERROR);
        }
        conExcellentCases.setId(null);
        conExcellentCases.setContractName(conShipping.getContractName());
        conExcellentCases.setContractNumber(conShipping.getContractNumber());
        conExcellentCases.setConId(conShipping.getId());
        conExcellentCases.setTypeOfContract(2);
        conExcellentCases.setApplicant(currentUserName);
        conExcellentCases.setCreateBy(SecurityUtils.getUsername());
        //启动审批流程
        ProcessInstanceParam param = new ProcessInstanceParam();
        param.setBussinessId(conShipping.getId());
        param.setBpmKey(BpmInstanceService.CON_RESOURCE_BOM_KEY);
        Map<String,Object> map = new HashMap<>();
        try {
            map = ObjectUtils.objectToMap(conExcellentCases);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        map.put("moduleName","船运合同");
        map.put("reason",conExcellentCases.getExcellent());
        map.put("serviceType",2);
        param.setParams(map);
        String processInstanceId = bpmInstanceService.startProcessInstance(param);
        conExcellentCases.setProcessInstanceId(processInstanceId);
        //conExcellentCases.setCreateBy(SecurityUtils.getUsername());
        conExcellentCasesService.save(conExcellentCases);
        conShipping.setExcellent(1);
        super.updateById(conShipping);
    }

    @Override
    public String saveCon(ConShipping conShipping) {
//        conShipping.setContractType(1);
        // 设置合同状态默认值为 已签订
//        if (conShipping.getFileType() == 1){
//            conShipping.setStatus(1);
//        }else if (conShipping.getFileType() == 2){
//            conShipping.setStatus(2);
//        }
        conShipping.setStatus(1);
        // 获取合同名字拼接字段
        conShipping.setContractName(editContractName(conShipping));

        conShipping.setContractNumber(editContractNumbers(conShipping));

        // 获取原始交付日期
        Date deliveryDateBegin = conShipping.getDeliveryDateBegin();
        // 获取租赁期限和租赁期限调整值
        BigDecimal leaseTermDown = conShipping.getLeaseTerm();
        Integer leaseTermValueUpDown = conShipping.getLeaseTermValueUpDown();
        // 如果租赁期限调整值不为空，则从租赁期限中减去它
        if (leaseTermValueUpDown != null) {
            leaseTermDown = leaseTermDown.subtract(BigDecimal.valueOf(leaseTermValueUpDown));
        }
        // 将交付日期转换为本地日期和时间
        LocalDateTime deliveryLocalDateTime = deliveryDateBegin.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 计算新的日期时间，将租赁期限添加到交付日期时间上
        LocalDateTime downResultLocalDateTime = deliveryLocalDateTime.plusDays(leaseTermDown.longValue());
        // 获取默认时区
        ZoneId zoneId = ZoneId.systemDefault();
        // 创建 ZonedDateTime 对象以保存带有时区信息的日期时间
        ZonedDateTime zonedDateTime = downResultLocalDateTime.atZone(zoneId);
        // 将 ZonedDateTime 转换为 Date
        Date downResult = Date.from(zonedDateTime.toInstant());

        conShipping.setRedeliveryDateBegin(downResult);

        Date deliveryDateEnd = conShipping.getDeliveryDateEnd();
        BigDecimal leaseTermUp = conShipping.getLeaseTerm();
        Integer leaseTermValueUp = conShipping.getLeaseTermValueUp();

        if (leaseTermValueUp != null) {
            leaseTermUp = leaseTermUp.add(BigDecimal.valueOf(leaseTermValueUp));
        }

        LocalDateTime deliveryLocalDateTimeEnd = deliveryDateEnd.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        LocalDateTime upResultLocalDateTime = deliveryLocalDateTimeEnd.plusDays(leaseTermUp.longValue());

        ZonedDateTime zonedDateTimeEnd = upResultLocalDateTime.atZone(zoneId);
        Date upResult = Date.from(zonedDateTimeEnd.toInstant());

        conShipping.setRedeliveryDateEnd(upResult);

        conShipping.setStartingDateOfLeaseBegin(conShipping.getDeliveryDateBegin());
        conShipping.setStartingDateOfLeaseEnd(conShipping.getRedeliveryDateEnd());

        super.save(conShipping);
        ConFiles conFile = new ConFiles();
        conFile.setConId(conShipping.getId());
        String url = conShipping.getFilePath();
        String path = url.replace(httpUrl, httpsUrl);
        conFile.setUrl(path);
        conFile.setNewUrl(path);//文字版
        if(conShipping.getFileType() == 1){
            conFile.setFileType(2);
            conFile.setFileName("term sheet-" + conShipping.getShipName());
        }else{
            conFile.setFileName(path.substring(path.lastIndexOf("/")+1,path.length()));
            conFile.setFileType(1);
            conFile.setScanPdf(FileUtil.getIsScanPdf(path));
        }

        SpInformation spInformation = new SpInformation();
        String imo = conShipping.getImo();
        String shipName = conShipping.getShipName();
        AtomicReference<Boolean> judge = new AtomicReference<>(true);
        List<SpInformation> allShip = spInformationMapper.getAllShipImo();
        Long num = allShip.stream().filter(s->s.getImo().equals(imo)).count();
        if(num.intValue()>0){
            judge.set(false);
        }
//        if(allShip!=null && allShip.size()>0){
//            allShip.stream().forEach(s->{
//                if(s.getImo().equals(imo) || s.getNameOfVessel().equals(shipName)){
//                  judge.set(false);
//                }
//            });
//        }
        if(judge.get()){

            //获取船旗国信息
            String county = remoteDispatchService.getShioCounty(conShipping.getShipName(),imo);
            if(county != null){
                spInformation.setCountry(county);
            }

            spInformation.setImo(imo);
            spInformation.setCountry("1");
            spInformation.setNameOfVessel(conShipping.getShipName());
            spInformation.setGrossTonnage(conShipping.getGrossTonnage());
            spInformation.setNetTonnage(conShipping.getNetTonnage());
            spInformation.setStorageCapacity(conShipping.getCabinCapacity());
            spInformation.setOilConsumption(BigDecimal.valueOf(9000));
            spInformation.setRentTimeSlot(conShipping.getRentTimeSlot());
            spInformationService.save(spInformation);
        }
        Long conId = conShipping.getId();
        conResourceMemorandumPositionMapper.updateConId(path, conId);
        //保存附件
        conFilesService.save(conFile);
        conOperateService.saveByCon("新增合同",conShipping.getId());

        //触发消息通知
        SysMessageSend messageSend = new SysMessageSend();
        messageSend.setMessageUrl(ModuleUrlEnum.CYHTXQ.getUrl()+conShipping.getId());
        messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_1.getCode());
        messageSend.setContentParam(new String[]{"船运合同"});
        remoteMessageSendService.messageSend(messageSend);

        return conId.toString();
    }

    @Override
    public void updateCon(ConShipping conShipping) {
        //获取原信息
        ConShipping OldConResourceMain = conShippingMapper.getById(conShipping.getId());
        //原合同编号尾号+1，方便比较
        String oldContractNumber = incrementLastDigit(OldConResourceMain.getContractNumber());
        conShipping.setContractName(editContractName(conShipping));

        String newContractNumbers = editContractNumbers(conShipping);
        if (newContractNumbers.equals(oldContractNumber)) {
            conShipping.setContractNumber(OldConResourceMain.getContractNumber());
        } else {
            conShipping.setContractNumber(newContractNumbers);
        }
        List<HireTimeDetails> hireTimeList = conShipping.getHireTime();

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "";
        try {
            //租金时间段
            if(conShipping.getRentList().size()>0){
                conShipping.getRentList().stream().forEach(c->{
                    c.setRentParagraphStr(c.getRentParagraphStr());
                });
                String rentListStr = objectMapper.writeValueAsString(conShipping.getRentList());
                conShipping.setRentTimeSlot(rentListStr);
            }
            //交船通知
            if(conShipping.getDeliveryNoticeList().size()>0){
                String deliveryNoticeStr = objectMapper.writeValueAsString(conShipping.getDeliveryNoticeList());
                conShipping.setDeliveryNotice(deliveryNoticeStr);
            }
            //还船通知
            if(conShipping.getRedeliveryNoticeList().size()>0){
                String redeliveryNoticeStr = objectMapper.writeValueAsString(conShipping.getRedeliveryNoticeList());
                conShipping.setRedeliveryNotice(redeliveryNoticeStr);
            }
            // 将 HireTimeDetails 对象列表转换为 JSON 字符串
            jsonString = objectMapper.writeValueAsString(hireTimeList);
//            System.out.println(jsonString);
//            // 可以通过 readValue 方法将 JSON 字符串还原为对象列表
//            List<HireTimeDetails> restoredList = objectMapper.readValue(jsonString, objectMapper.getTypeFactory().constructCollectionType(List.class, HireTimeDetails.class));
//            System.out.println(restoredList);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        //租金时间段
//        if(conShipping.getRentList().size()>0){
//           Date minRentDate = conShipping.getRentList().stream().min(Comparator.comparing(p->p.getRentDateBegin())).get().getRentDateBegin();
//           Date maxRentDate = conShipping.getRentList().stream().max(Comparator.comparing(p->p.getRentDateEnd())).get().getRentDateEnd();
//            conShipping.setRedeliveryDateBegin(minRentDate);
//            conShipping.setRedeliveryDateEnd(maxRentDate);
//        }

        conShipping.setHireTimeValue(jsonString);

        if(StringUtils.isNotBlank(conShipping.getDeliveryFuelQuantitySymbol())){
          conShipping.setDeliveryFuelQuantitySymbol(HtmlUtils.htmlUnescape(conShipping.getDeliveryFuelQuantitySymbol()));
        }
        if(StringUtils.isNotBlank(conShipping.getRefundFuelQuantitySymbol())){
            conShipping.setRefundFuelQuantitySymbol(HtmlUtils.htmlUnescape(conShipping.getRefundFuelQuantitySymbol()));
        }
        if(StringUtils.isNotBlank(conShipping.getVlDeliveryFuelQuantitySymbol())){
            conShipping.setVlDeliveryFuelQuantitySymbol(HtmlUtils.htmlUnescape(conShipping.getVlDeliveryFuelQuantitySymbol()));
        }
        if(StringUtils.isNotBlank(conShipping.getVlRefundFuelQuantitySymbol())){
            conShipping.setVlRefundFuelQuantitySymbol(HtmlUtils.htmlUnescape(conShipping.getVlRefundFuelQuantitySymbol()));
        }
        if(StringUtils.isNotBlank(conShipping.getDeliveryLngVolumeSymbol())){
            conShipping.setDeliveryLngVolumeSymbol(HtmlUtils.htmlUnescape(conShipping.getDeliveryLngVolumeSymbol()));
        }
        if(StringUtils.isNotBlank(conShipping.getLngQuantityReturnedToTheShipSymbol())){
            conShipping.setLngQuantityReturnedToTheShipSymbol(HtmlUtils.htmlUnescape(conShipping.getLngQuantityReturnedToTheShipSymbol()));
        }
        super.updateById(conShipping);

        ConExcellentCases conExcellentCases = conExcellentCasesService.getAllByConId(conShipping.getId());
        if (conExcellentCases != null) {
            conExcellentCases.setContractName(conShipping.getContractName());
            conExcellentCases.setContractNumber(conShipping.getContractNumber());
            conExcellentCasesService.updateById(conExcellentCases);
        }

        SpInformation spInformation = new SpInformation();
        String imo = conShipping.getImo();
        String shipName = conShipping.getShipName();
        String contractName = conShipping.getContractName();
        BigDecimal cabinCapacity = conShipping.getCabinCapacity();

        Boolean isUpdate = !StringUtils.equals(imo,OldConResourceMain.getImo())
                || !StringUtils.equals(shipName,OldConResourceMain.getShipName())
                || !StringUtils.equals(contractName,OldConResourceMain.getContractName())
                || OldConResourceMain.getCabinCapacity().compareTo(cabinCapacity) != 0;

        if (isUpdate) {
            //获取船旗国信息
            String county = remoteDispatchService.getShioCounty(conShipping.getShipName(),imo);

            //更新船舶信息
            LambdaUpdateWrapper<SpInformation> shipWra = new LambdaUpdateWrapper<SpInformation>();
            shipWra.eq(SpInformation::getImo,OldConResourceMain.getImo());
            shipWra.set(SpInformation::getImo,imo);
            shipWra.set(SpInformation::getNameOfVessel,shipName);
            if(county != null){
                shipWra.set(SpInformation::getCountry,county);
            }
            shipWra.set(SpInformation::getRentTimeSlot,conShipping.getRentTimeSlot());
            shipWra.set(SpInformation::getStorageCapacity,conShipping.getCabinCapacity());
            shipWra.set(SpInformation::getGrossTonnage,conShipping.getGrossTonnage());
            shipWra.set(SpInformation::getNetTonnage,conShipping.getNetTonnage());
            spInformationService.update(shipWra);

            //更新船舶关联的其他信息
            ShipInfoUpdateDto updateShipInfo = new ShipInfoUpdateDto();
            updateShipInfo.setImo(OldConResourceMain.getImo());
            updateShipInfo.setShipImo(conShipping.getImo());
            updateShipInfo.setShipName(conShipping.getShipName());
            updateShipInfo.setCabinCapacity(conShipping.getCabinCapacity());
            updateShipInfo.setContractName(conShipping.getContractName());
            updateShipInfo.setTradeBody(conShipping.getTradeBody());
            remoteDispatchService.updateShipInfo(updateShipInfo);
        }

        conOperateService.saveByCon("修改合同", conShipping.getId());

        //触发消息通知
        SysMessageSend messageSend = new SysMessageSend();
        messageSend.setMessageUrl(ModuleUrlEnum.CYHTXQ.getUrl()+conShipping.getId());
        messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_2.getCode());
        messageSend.setContentParam(new String[]{conShipping.getShipName(),conShipping.getContractNumber()});
        remoteMessageSendService.messageSend(messageSend);
    }

    @Override
    public void supplementaryContractFile(ConFiles conFiles) {
        ConShipping conShipping = super.getById(conFiles.getConId());
        if(conShipping == null){
            throw new BusException("该合同不存在!",BaseResultCode.GENERAL_ERROR);
        }
//        if(conShipping.getFileType() != 1){
//            throw new BusException("该合同不能补充合同原件!",BaseResultCode.GENERAL_ERROR);
//        }
        conShipping.setFileType(2);
        conShipping.setStatus(2);
        super.updateById(conShipping);
        conFiles.setFileType(1);
        String path = conFiles.getUrl();
        conFiles.setFileName(path.substring(path.lastIndexOf("/")+1,path.length()));
        conFiles.setScanPdf(FileUtil.getIsScanPdf(path));
        //保存附件
        conFilesService.save(conFiles);
    }

    //根据信息拼接合同名字
    @Override
    public String editContractName(ConShipping conShipping){
        String str1 = constantMapper.findConstLabel("船运合同类型", String.valueOf(conShipping.getContractType()));
        String str2 = constantMapper.findConstLabel("贸易主体", String.valueOf(conShipping.getTradeBody()));
        LocalDate currentDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        String signingDate = currentDate.format(formatter);
//        Date signingDate = conShipping.getSigningDate();
//        SimpleDateFormat sdf = new SimpleDateFormat("YYYY.MM.dd");
//        String str3 = sdf.format(signingDate);
        String str4 = conShipping.getShipName();
        // 合同名字拼接
        String ContractName = "TCP-"+str1+"-"+str4+"-"+str2+"-"+signingDate;
        return ContractName;
    }

    //根据信息拼接合同编号
    @Override
    public String editContractNumbers(ConShipping conShipping){
        // 获取所有合同编号
        List<String> strings = conShippingMapper.getAllContractNumbers();
        // 创建合同编号对象
        String ContractNum = null;
        // 合同编号拼接
        if (conShipping.getContractType() == 1){
            int maxNumber = extractAndFindMaxNumber(strings, "TCP-ZRCQC");
            ContractNum = "TCP-ZRCQC-"+maxNumber;
        }else if (conShipping.getContractType() == 2){
            int maxNumber = extractAndFindMaxNumber(strings, "TCP-ZRDQC");
            ContractNum = "TCP-ZRDQC-"+maxNumber;
        }else if (conShipping.getContractType() == 3){
            int maxNumber = extractAndFindMaxNumber(strings, "TCP-CBZC");
            ContractNum = "TCP-CBZC-"+maxNumber;
        }else if (conShipping.getContractType() == 4){
            int maxNumber = extractAndFindMaxNumber(strings, "TCP-NBZZ");
            ContractNum = "TCP-NBZZ-"+maxNumber;
        }
        return ContractNum;
    }

    @Override
    public List<ConResourceMemorandumPosition> getFieldLocation(Long ids) {
        return conResourceMemorandumPositionService.getFieldLocation(ids);
    }

    @Override
    public void contractExpireMessageSend() {
        //即将到期
        List<ConShipping> contractList = this.baseMapper.selectList(
                new LambdaQueryWrapper<ConShipping>()
                        .ge(ConShipping::getStartingDateOfLeaseEnd,new Date())
        );
        List<SysMessageSend> messageSendList = new LinkedList<>();
        if(contractList.size() > 0){
            for (ConShipping contractInfo : contractList) {
                //初次提醒
                SysMessageSend messageSend = new SysMessageSend();
                messageSend.setMessageUrl(ModuleUrlEnum.CYHTXQ.getUrl()+contractInfo.getId());
                messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_14.getCode());
                messageSend.setContentParam(new String[]{contractInfo.getContractName()
                        ,contractInfo.getContractNumber()
                        , DateUtils.parseDateToStr("yyyy-MM-dd",contractInfo.getStartingDateOfLeaseEnd())});
                messageSend.setCompareType(5);
                messageSend.setCompareValue(DateUtil.getDateDays(new Date(),contractInfo.getStartingDateOfLeaseEnd(),1).intValue());
                messageSendList.add(messageSend);

                //二次提醒
                SysMessageSend messageSendTwo = new SysMessageSend();
                messageSendTwo.setMessageUrl(ModuleUrlEnum.CYHTXQ.getUrl()+contractInfo.getId());
                messageSendTwo.setMessageType(MessageTypeEnum.MESSAGE_TYPE_15.getCode());
                messageSendTwo.setContentParam(new String[]{contractInfo.getContractName()
                        ,contractInfo.getContractNumber()
                        , DateUtils.parseDateToStr("yyyy-MM-dd",contractInfo.getStartingDateOfLeaseEnd())});
                messageSendTwo.setCompareType(5);
                messageSendTwo.setCompareValue(DateUtil.getDateDays(new Date(),contractInfo.getStartingDateOfLeaseEnd(),1).intValue());
                messageSendList.add(messageSendTwo);
            }
        }

        //到期提醒（还船时间当天）
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date zeroPoint = calendar.getTime();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date twentyThreePoint = calendar.getTime();
        List<ConShipping> contractListCurrent = this.baseMapper.selectList(
                new LambdaQueryWrapper<ConShipping>()
                        .ge(ConShipping::getStartingDateOfLeaseEnd,zeroPoint)
                        .le(ConShipping::getStartingDateOfLeaseEnd,twentyThreePoint)
        );
        if(contractListCurrent.size() > 0){
            for (ConShipping contractInfo : contractListCurrent) {
                SysMessageSend messageSend = new SysMessageSend();
                messageSend.setMessageUrl(ModuleUrlEnum.CYHTXQ.getUrl()+contractInfo.getId());
                messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_16.getCode());
                messageSend.setContentParam(new String[]{contractInfo.getContractName()
                        ,contractInfo.getContractNumber()});
                messageSendList.add(messageSend);
            }
        }

        //已过期提醒
        Date compareTime = cn.hutool.core.date.DateUtil.offsetDay(new Date(),-1);
        calendar.setTime(compareTime);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startPoint = calendar.getTime();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endPoint = calendar.getTime();
        List<ConShipping> contractListOver = this.baseMapper.selectList(
                new LambdaQueryWrapper<ConShipping>()
                        .ge(ConShipping::getStartingDateOfLeaseEnd,startPoint)
                        .le(ConShipping::getStartingDateOfLeaseEnd,endPoint)
        );
        if(contractListOver.size() > 0){
            for (ConShipping contractInfo : contractListOver) {
                SysMessageSend messageSend = new SysMessageSend();
                messageSend.setMessageUrl(ModuleUrlEnum.CYHTXQ.getUrl()+contractInfo.getId());
                messageSend.setMessageType(MessageTypeEnum.MESSAGE_TYPE_17.getCode());
                messageSend.setContentParam(new String[]{contractInfo.getContractName()
                        ,contractInfo.getContractNumber()});
                messageSendList.add(messageSend);
            }
        }
        if(messageSendList.size() == 0){
            return;
        }
        remoteMessageSendService.messageSendBatch(messageSendList);
    }

    /**
     * 船舶名称筛选船舶信息
     * @param name
     * @return
     */
    @Override
    public List<IhsShipBaseVo> getIhsShipInfo(String name){
        List<IhsShipBaseVo> shipBaseVos = new ArrayList<>();
        if(StringUtils.isNotBlank(name)){
            name = name.toUpperCase();
        }
        List<IhsShipBaseList> ihsShipBases = ihsShipBaseMapper.selectList(new LambdaQueryWrapper<IhsShipBaseList>().likeRight(StringUtils.isNotBlank(name),IhsShipBaseList::getShipName,name));
        if(null != ihsShipBases && ihsShipBases.size()>0){
            ihsShipBases.stream().forEach(i->{
                IhsShipBaseVo ihsShipBaseVo = new IhsShipBaseVo();
                BeanUtils.copyProperties(i,ihsShipBaseVo);
                shipBaseVos.add(ihsShipBaseVo);
            });
        }
        return shipBaseVos;
    }


    /**
     * 船舶名称筛选船舶信息
     * @param imo
     * @return
     */
    @Override
    public List<IhsShipBaseVo> getIhsShipInfoByImo(String imo){
        List<IhsShipBaseVo> shipBaseVos = new ArrayList<>();
        List<IhsShipBaseList> ihsShipBases = ihsShipBaseMapper.selectList(new LambdaQueryWrapper<IhsShipBaseList>().likeRight(StringUtils.isNotBlank(imo),IhsShipBaseList::getImo,imo));
        if(null != ihsShipBases && ihsShipBases.size()>0){
            ihsShipBases.stream().forEach(i->{
                IhsShipBaseVo ihsShipBaseVo = new IhsShipBaseVo();
                BeanUtils.copyProperties(i,ihsShipBaseVo);
                shipBaseVos.add(ihsShipBaseVo);
            });
        }
        return shipBaseVos;
    }

    @Override
    public List<String> queryShipNameList(String shipName) {
        return baseMapper.queryShipNameList(shipName);
    }

    /**
     * 船运合同列表
     * @return
     */
    @Override
    public List<ConShippingVo> getConShippingNames(String name){
        List<ConShippingVo> conShippingVos = new ArrayList<>();
        LambdaQueryWrapper<ConShipping> lambdaQueryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank(name)){
            lambdaQueryWrapper.likeRight(ConShipping::getShipName,name);
        }
        List<ConShipping> conShippings = this.list(lambdaQueryWrapper);
        if(null != conShippings && conShippings.size()>0){
            conShippings.stream().forEach(c->{
                ConShippingVo conShippingVo = new ConShippingVo();
                BeanUtils.copyProperties(c,conShippingVo);
                conShippingVos.add(conShippingVo);
            });
        }
        return conShippingVos;
    }

    /**
     * 船员管理中根据船舶名称查询船运合同id
     * @param shipName
     * @return
     */
    @Override
    public String queryConIdByShipName(String shipName) {
        List<ConShipping> conShippings = baseMapper.selectList(new LambdaQueryWrapper<ConShipping>().eq(ConShipping::getShipName,shipName));
        String id = "";
        if(null != conShippings && conShippings.size()>0){
            id = conShippings.get(0).getId().toString();
        }
        return id;
    }

    @Override
    public Page<ConShipping> export(ConShipping conShipping) {
        Page<ConShipping> page = this.page(conShipping, new QueryWrapper<ConShipping>().ne("del_apply",2));
        if (null != page) {
            List<ConShipping> conShippings = page.getList();
            if (null != conShippings && conShippings.size() > 0) {
                conShippings.stream().forEach(c -> {
                    StringBuilder result = new StringBuilder();
                    StringBuilder deliveryNoticeDetailResult = new StringBuilder();
                    StringBuilder redeliveryNoticeDetailResult = new StringBuilder();
                    ObjectMapper objectMapper = new ObjectMapper();

                    if (com.ship.common.core.utils.StringUtils.isNotEmpty(c.getRentTimeSlot())) {
                        try {
                            List<ConShippingRent> shipRentList = objectMapper.readValue(c.getRentTimeSlot(), new TypeReference<List<ConShippingRent>>() {
                            });
                            if (null != shipRentList && shipRentList.size() > 0) {
                                shipRentList.stream().forEach(s -> {
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    if (com.ship.common.core.utils.StringUtils.isNotBlank(result.toString())) {
                                        result.append(System.lineSeparator());
                                        result.append(df.format(s.getRentDateBegin()) + "至" + df.format(s.getRentDateEnd()) + ",租金：" + s.getRentParagraphStr());
                                    } else {
                                        result.append(df.format(s.getRentDateBegin()) + "至" + df.format(s.getRentDateEnd()) + ",租金：" + s.getRentParagraphStr());
                                    }
                                });
                            }
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                        c.setRentTimeSlot(result.toString());
                    }
                    if (com.ship.common.core.utils.StringUtils.isNotEmpty(c.getDeliveryNotice())) {
                        //交船通知规则
                        List<DeliveryNoticeDetail> deliveryNoticeDetailList = null;
                        try {
                            deliveryNoticeDetailList = objectMapper.readValue(c.getDeliveryNotice(), new TypeReference<List<DeliveryNoticeDetail>>() {
                            });
                            if (null != deliveryNoticeDetailList && deliveryNoticeDetailList.size() > 0) {
                                deliveryNoticeDetailResult.append("交船前 ");
                                deliveryNoticeDetailList.stream().forEach(s -> {
                                    deliveryNoticeDetailResult.append(s.getDeliveryNoticeDay()+"天 ");
                                });
                            }
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                        c.setDeliveryNotice(deliveryNoticeDetailResult.toString());
                    }
                    if (com.ship.common.core.utils.StringUtils.isNotEmpty(c.getRedeliveryNotice())) {
                        //还船通知规则
                        List<DeliveryNoticeDetail> redeliveryNoticeDetailList = null;
                        try {
                            redeliveryNoticeDetailList = objectMapper.readValue(c.getRedeliveryNotice(), new TypeReference<List<DeliveryNoticeDetail>>() {
                            });
                            if (null != redeliveryNoticeDetailList && redeliveryNoticeDetailList.size() > 0) {
                                redeliveryNoticeDetailResult.append("还船前 ");
                                redeliveryNoticeDetailList.stream().forEach(s -> {
                                    redeliveryNoticeDetailResult.append(s.getDeliveryNoticeDay()+"天 ");
                                });
                            }
                        } catch (JsonProcessingException e) {
                            throw new RuntimeException(e);
                        }
                        c.setRedeliveryNotice(redeliveryNoticeDetailResult.toString());
                    }
                });
            }
        }
        return page;
    }

    /**
     * 1:船级社/2:船东/3:租家/4:航运经纪人
     * @param num
     * @return
     */
    @Override
    public List<ConShippingNameTextVo> selectConShippingNameTexts(Integer num){
        List<ConShippingNameTextVo> nameTextVos = new ArrayList<>();
        if(num.equals(1)){
            nameTextVos = conShippingMapper.getAllClassificationSociety();
        }else if(num.equals(2)){
            nameTextVos = conShippingMapper.getAllShipowner();
        }else if(num.equals(3)){
            nameTextVos = conShippingMapper.getAllTenant();
        }else if(num.equals(4)){
            nameTextVos = conShippingMapper.getAllShipBroker();
        }
        return nameTextVos;
    }
}
